/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.extns.location;

import javax.microedition.location.Criteria;
import javax.microedition.location.LocationProvider;

public class DeviceLocation {

	private static DeviceLocation locationInstance;

	public static DeviceLocation getLocation(Criteria criteria) {
		if (locationInstance == null)
			locationInstance = new DeviceLocation(criteria);
		return locationInstance;
	}

	private LocationProvider locationProvider;

	private DeviceLocation(Criteria criteria) {
		try {
			// Criteria criteria = new Criteria();
			locationProvider = LocationProvider.getInstance(criteria);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	public void getCurrentLocation(double coords[]) {
		try {
			javax.microedition.location.QualifiedCoordinates qualifiedCoordinates = locationProvider.getLocation(30)
					.getQualifiedCoordinates();
			coords[0] = qualifiedCoordinates.getLatitude();
			coords[1] = qualifiedCoordinates.getLongitude();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * Returns the google map tile url for the given coordinates The image is of
	 * PNG-32 format
	 * 
	 * @param latitude
	 * @param longitude
	 * @param zoomLevel
	 *            less than 17
	 * @param tileWidth
	 * @param tileHeight
	 * @param apiKey
	 *            Google developer API key
	 * @return
	 */
	public String getGoogleCoorURL(double latitude, double longitude, int zoomLevel, int tileWidth, int tileHeight,
			String apiKey) {

		StringBuffer buf = new StringBuffer("http://maps.google.com/staticmap?center=");
		buf.append(Double.toString(latitude));
		buf.append(',');
		buf.append(Double.toString(longitude));
		buf.append("&format=png32");
		buf.append("&zoom=");
		buf.append(zoomLevel);
		buf.append("&size=");
		buf.append(tileWidth);
		buf.append('x');
		buf.append(tileHeight);
		buf.append("&key=");
		buf.append(apiKey);
		return buf.toString();
	}

	public void location(double coords[]) {
		locationInstance.getCurrentLocation(coords);
	}

	/*
	 * public String getCoordinates(String address){ return
	 * "http://maps.google.com/maps/geo?q=" + urlEncode(address) +
	 * "&output=csv&key=" + apiKey; }
	 */
}
